package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"github.com/gogf/gf/os/glog"
	"net/http"
)

type ErrorController struct {
	beego.Controller
}

func (o *ErrorController) Error403() {
	o.TplName = "admin/error/403.html"
}

func (o *ErrorController) Error404() {
	o.TplName = "admin/error/404.html"
}

func (o *ErrorController) Error500() {
	o.TplName = "admin/error/500.html"
}

type BaseController struct {
	beego.Controller
}

func (o *BaseController) Download(file string, ContentType string) {
	o.Ctx.Output.Header("Content-Type", ContentType)
	http.ServeFile(o.Ctx.Output.Context.ResponseWriter, o.Ctx.Output.Context.Request, file)
}

func (o *BaseController) LoadRequest(request interface{}) (err error) {
	if err = json.Unmarshal(o.Ctx.Input.RequestBody, request); err != nil {
		glog.Debug(o.Ctx.Input.RequestBody)
		return err
	} else {
		err = o.Validation(request)
		return err
	}
}

func (o *BaseController) Validation(request interface{}) error {
	valid := validation.Validation{}
	if b, err := valid.Valid(request); err != nil {
		return err
	} else {
		if !b {
			for _, e := range valid.Errors {
				return e
			}
		}
	}
	return nil
}

type AjaxController struct {
	BaseController
}

func (o *AjaxController) DataTableResponse(data interface{}, total int64, message interface{}) {
	o.Data["json"] = map[string]interface{}{"code": 0, "msg": message, "count": total, "data": data}
	o.ServeJSON()
}

func (o *AjaxController) MessageResponse(message interface{}) {
	o.Data["json"] = map[string]interface{}{"code": 0, "msg": message}
	o.ServeJSON()
}

func (o *AjaxController) ErrorResponse(err error) {
	o.Data["json"] = map[string]interface{}{"code": 1, "msg": err.Error()}
	o.ServeJSON()
}

func (o *AjaxController) DataResponse(data interface{}) {
	o.Data["json"] = map[string]interface{}{"code": 0, "msg": "ok", "data": data}
	o.ServeJSON()
}
